package com.dbq.fast.util;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

public class TimeOutHandler {

    public static final int TIME_OUT_COUNT = 10; //计时数，单位秒

    private static Timer timer;
    private ITimeOutListener listener;

    public void startTiming(){
        resetTimer();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            AtomicInteger count = new AtomicInteger(TIME_OUT_COUNT);

            @Override
            public void run() {
                count.decrementAndGet();
                if (count.get() < 0) {
                    if(listener != null){
                        listener.timeOut();
                    }
                    resetTimer();
                }
            }

        }, 0L, 1000L);
    }

    /**
     *
     * @param timeCount 几个1秒
     */
    public void startTiming(int timeCount){
        resetTimer();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            AtomicInteger count = new AtomicInteger(timeCount);

            @Override
            public void run() {
                count.decrementAndGet();
                if (count.get() < 0) {
                    if(listener != null){
                        listener.timeOut();
                    }
                    resetTimer();
                }
            }

        }, 0L, 1000L);
    }

    public void resetTimer() {
        if (timer != null) {
            synchronized (timer) {
                if (timer != null) {
                    timer.cancel();
                    timer.purge();
                    timer = null;
                }
            }
        }
    }

    public interface ITimeOutListener{
        void timeOut();
    }

    public void setTimeOutListener(ITimeOutListener listener){
        this.listener = listener;
    }

}
